Page({
  data: {
    orderInfo: {
      gname: '', // 商品名称
      price: 0, // 商品价格
      prove: '', // 商品图片
      address: '', // 服务地址
      date: '', // 预约时间
      phone: '', // 联系电话
      rate: 0, // 优惠券折扣
      gid: '' // 商品ID
    },
    totalPrice: 0,
    discountPrice: 0,
    userInfo: null
  },

  onLoad: function(options) {
    // 检查登录状态
    const isLogin = wx.getStorageSync('isLogin')
    const userInfo = wx.getStorageSync('userInfo')
    
    if (!isLogin || !userInfo) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }

    this.setData({
      userInfo: userInfo
    })

    if (options.goodsId) {
      this.loadOrderDetail(userInfo.id, options.goodsId)
    }
  },

  // 加载订单详情
  loadOrderDetail: function(userId, goodsId) {
    wx.request({
      url: 'http://localhost:9205/order/selectOrder',
      method: 'GET',
      data: {
        id: userId
      },
      success: (res) => {
        if (res.data) {
          const orderInfo = res.data
          orderInfo.gid = goodsId // 保存商品ID
          // 计算优惠后价格
          const totalPrice = orderInfo.price
          const discountPrice = orderInfo.rate ? (totalPrice * (100 - orderInfo.rate) / 100) : totalPrice

          this.setData({
            orderInfo: orderInfo,
            totalPrice: totalPrice,
            discountPrice: discountPrice
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取订单信息失败',
          icon: 'none'
        })
      }
    })
  },

  // 提交订单
  submitOrder: function() {
    if (!this.data.userInfo) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }

    const orderData = {
      oid: this.data.currentOid,
      nid: this.data.userInfo.id,
      gid: this.data.orderInfo.gid,
      address: this.data.orderInfo.address || '河北省保定市万博广场',
      phone: this.data.orderInfo.phone || '15630352072',
      date: this.data.orderInfo.date,
      duration: 2,
      status: 0,
      price: this.data.discountPrice
    }

    console.log('提交订单数据:', orderData);

    wx.request({
      url: 'http://localhost:9205/order/add',
      method: 'POST',
      data: orderData,
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            currentOid: this.data.currentOid + 1
          });
          
          wx.showToast({
            title: '预约成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/ucenter/order/order'
            })
          }, 1500)
        } else {
          wx.showToast({
            title: '预约失败，请重试',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '预约失败，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack()
  }
}) 